<?php

class Ebx_EventHandler {

	const CLASS_PREFIX = 'Ebx_EventHandler';

	protected $_objects = array();

	protected $_classPrefix = null;

	function attachObject($object, $options = array(), $callParams = array(), $code = null) {
		if ($code === null) {
			$code = count($this->_objects);
		}
		$this->_objects[$code] = array(
			'object' => $object,
			'options' => $options,
			'callParams' => $callParams
		);
	}

	function setClassPrefix($prefix) {
		$this->_classPrefix = $prefix;
	}

	function handle($event, &$args) {
		foreach ($this->_objects as $key => $options) {
			//проверяем, подходит ли вызываемый объект под параметры события
			$checkOptions = array_intersect_key((array)$args, $options['callParams']);
			if (!$checkOptions || !array_intersect_assoc($options['callParams'], $checkOptions)) {
				continue;
			}

			if (is_string($options['object'])) {
				$object = $this->_getObject($options['object'], $options['options']);
				$this->_objects[$key]['object'] = $object;
			} else {
				$object = $options['object'];
			}
			if (method_exists($object, $event)) {
				$result = $object->$event($args);
				if (false === $result) {
					return $result;
				}
			}
		}

		return true;
	}

	protected function _getObject($objectName, $options = array()) {
		if ($this->_classPrefix) {
			$class = $this->_classPrefix.'_'.ucfirst($objectName);
		} else {
			$class = self::CLASS_PREFIX.'_'.ucfirst($objectName);
		}
		return new $class($options);
	}

	function __call($name, &$args) {
		return $this->handle($name, $args[0]);
	}

}

?>